package com.zhihao.zhihaopicturebackend.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhihao.zhihaopicturebackend.annotation.AuthCheck;
import com.zhihao.zhihaopicturebackend.common.BaseResponse;
import com.zhihao.zhihaopicturebackend.common.DeleteRequest;
import com.zhihao.zhihaopicturebackend.common.ResultUtils;
import com.zhihao.zhihaopicturebackend.constant.UserConstant;
import com.zhihao.zhihaopicturebackend.exception.BusinessException;
import com.zhihao.zhihaopicturebackend.exception.ErrorCode;
import com.zhihao.zhihaopicturebackend.exception.ThrowUtils;
import com.zhihao.zhihaopicturebackend.model.dto.user.*;
import com.zhihao.zhihaopicturebackend.model.entity.SystemUser;
import com.zhihao.zhihaopicturebackend.model.vo.LoginUserVO;
import com.zhihao.zhihaopicturebackend.model.vo.UserVO;
import com.zhihao.zhihaopicturebackend.service.SystemUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * @author Jackson
 * @create 2024/12/20 19:24
 * @description 用户管理
 */
//@Api(value = "用户管理",tags = "用户管理")
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private SystemUserService systemUserService;

    /**
     * 用户注册
     */
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@Valid @RequestBody UserRegisterRequest userRegisterRequest){
        if (ObjectUtil.isNull(userRegisterRequest)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long userId = systemUserService.userRegister(userRegisterRequest);
        return ResultUtils.success(userId);
    }

    /**
     * 用户登录
     *  新阶段的权限校验体系是
     *      1. tomcat自带的HttpServletRequest中的session会话中保存用户信息
     *      2. sa-token认证框架(所以登录后也需要将用户登录信息写入到sa-token)
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public BaseResponse<LoginUserVO> userLogin(@Valid @RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (ObjectUtil.isNull(userLoginRequest)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        LoginUserVO loginUserVO = systemUserService.userLogin(userLoginRequest, request);
        return ResultUtils.success(loginUserVO);
    }

    /**
     * 用户注销
     */
    @ApiOperation("用户注销")
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        boolean result = systemUserService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取脱敏的已登录用户信息
     */
    @ApiOperation("获取当前登录用户信息")
    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        SystemUser loginUser = systemUserService.getLoginUser(request);
        LoginUserVO loginUserVO = BeanUtil.copyProperties(loginUser, LoginUserVO.class);
        return ResultUtils.success(loginUserVO);
    }

    /**
     * 创建用户
     */
    @ApiOperation("管理员创建用户")
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest) {
        ThrowUtils.throwIf(userAddRequest == null, ErrorCode.PARAMS_ERROR);
        SystemUser user = BeanUtil.copyProperties(userAddRequest, SystemUser.class);
        // 默认密码 12345678
        final String DEFAULT_PASSWORD = "123456789";
        String encryptPassword = systemUserService.getEncryptPassword(DEFAULT_PASSWORD);
        user.setUserPassword(encryptPassword);
        boolean result = systemUserService.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());
    }

    /**
     * 用户修改密码
     */
    @ApiOperation("用户修改密码")
    @PostMapping("/modifyPassword")
    public BaseResponse<Boolean> modifyPassword(@Valid @RequestBody UserPasswordModifyRequest userPasswordModifyRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(userPasswordModifyRequest == null, ErrorCode.PARAMS_ERROR);
        Boolean result = systemUserService.modifyUserPassword(userPasswordModifyRequest, request);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取用户（仅管理员）
     */
    @ApiOperation("管理员获取用户")
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<SystemUser> getUserById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        SystemUser user = systemUserService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 根据 id 获取包装类
     */
    @ApiOperation("获取用户(用户间调用)")
    @GetMapping("/get/vo")
    public BaseResponse<UserVO> getUserVOById(long id) {
        BaseResponse<SystemUser> response = getUserById(id);
        SystemUser user = response.getData();
        return ResultUtils.success(systemUserService.getUserVO(user));
    }

    /**
     * 删除用户
     */
    @ApiOperation("管理员删除用户")
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = systemUserService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新用户
     */
    @ApiOperation("管理员更新用户")
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        SystemUser user = new SystemUser();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = systemUserService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 分页获取用户封装列表（仅管理员）
     *
     * @param userQueryRequest 查询请求参数
     */
    @ApiOperation("管理员分页获取用户列表")
    @PostMapping("/list/page/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest) {
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);
        long current = userQueryRequest.getCurrent();
        long pageSize = userQueryRequest.getPageSize();
        Page<SystemUser> userPage = systemUserService.page(new Page<>(current, pageSize),
                systemUserService.getQueryWrapper(userQueryRequest));
        Page<UserVO> userVOPage = new Page<>(current, pageSize, userPage.getTotal());
        List<UserVO> userVOList = systemUserService.getUserVOList(userPage.getRecords());
        userVOPage.setRecords(userVOList);
        return ResultUtils.success(userVOPage);
    }

}
